#include "dht11.h"
#include "U8glib.h"
U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE);

//-------字体设置，大、中、小
#define setFont_L u8g.setFont(u8g_font_fub25n)
#define setFont_M u8g.setFont(u8g_font_7x13)
#define setFont_S u8g.setFont(u8g_font_fixed_v0r)

unsigned int tempMax = 80;
int measurePin = A2;            
int ledPower = 12;              
 
unsigned int samplingTime = 280;
unsigned int deltaTime = 40;
unsigned int sleepTime = 9680;

int sensor_value = 0; 

float voMeasured = 0;
float calcVoltage = 0;
float dustDensity = 0;

dht11 DHT11;
#define DHT11PIN 4.

void setup(){
  Serial.begin(9600);
  pinMode(ledPower,OUTPUT);
  pinMode(A1, INPUT);
//   analogReference(INTERNAL); //调用板载1.1V基准源
 pinMode(6, OUTPUT);
digitalWrite(6, LOW);
}
 
void loop(){
  digitalWrite(ledPower,LOW);
  delayMicroseconds(samplingTime);
 
  voMeasured = analogRead(measurePin);//将模拟数据（A2）赋值给变量//
  sensor_value = analogRead(A1);//将模拟数据（A0）赋值给变量//亮度
  int chk = DHT11.read(DHT11PIN);  //读取温湿度传感器数据
  // double analogVotage = 1.1*(double)analogRead(A3)/1023;
  float temp = (float)DHT11.temperature; //计算温度
 
  delayMicroseconds(deltaTime);
  digitalWrite(ledPower,HIGH);
  delayMicroseconds(sleepTime);
  // voMeasured=200;
  calcVoltage = voMeasured*(5.0/1024);
  dustDensity = 0.17*calcVoltage-0.1;
 
  if ( dustDensity < 0)
  {
    dustDensity = 0.00;
  }
  if (temp < tempMax) { //小于报警门限
   digitalWrite(6, LOW);
  }
  else{ //发光二极管亮度最大值，并启动声音报警
    digitalWrite(6, HIGH);
  }
  
  Serial.println(sensor_value);//串口输出亮度数值

  Serial.println("Raw Signal Value (0-1023):");
  Serial.println(voMeasured);
 
 
  Serial.println("Dust Density:");
  Serial.println(dustDensity);
  Serial.print("Humidity 湿度 (%): ");                //在串口监视器打印标题 “Humidity 湿度 (%):”
  Serial.println((float)DHT11.humidity, 2);          //在串口监视器打印湿度模拟值

  Serial.print("Temperature 温度 (C): ");            //在串口监视器打印标题 “Temperature 温度 (C):”
  Serial.println((float)DHT11.temperature, 2);      //在串口监视器打印温度模拟值
 
   u8g.firstPage();
   do{
    setFont_S;//字体大小
      u8g.setPrintPos(0,8);
      u8g.print("luminance: ");u8g.print(sensor_value);
      u8g.setPrintPos(0,23);
      u8g.print("Dust Density: ");u8g.print(dustDensity);
      u8g.setPrintPos(0,40);
      u8g.print("Humidity (%): ");u8g.print((float)DHT11.humidity);
      u8g.setPrintPos(0,60);
      u8g.print("Temperature (%): ");u8g.print((float)DHT11.temperature);
   }while (u8g.nextPage());


  delay(1000);
}